#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import yaml
import MySQLdb
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.ensemble import RandomForestClassifier
import csv
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt
import time
import datetime
import scipy as sp


def dtime(dt):
    #12/07/2014-22:44:37.169789 - 1405201477.0
    #myDate = "12/07/2014-22:44:37.169789"
    #myDate = "2014-08-01 04:41:52,117"
    epoch = datetime.datetime.utcfromtimestamp(0) # start of epoch time
    my_time = datetime.datetime.strptime(dt, "%d/%m/%Y-%H:%M:%S.%f") # plugin your time object
    delta = my_time - epoch
    return delta.total_seconds() * 1000.0

    #timestamp = time.mktime(datetime.datetime.strptime(dt, "%d/%m/%Y-%H:%M:%S.%f").timetuple())
    #return timestamp

#EFETUA LIGACAO
def db_establish_conn(yaml_options):
    try:
        database = MySQLdb.connect(host=yaml_options['Database']['host'],user=yaml_options['Database']['user'],passwd=yaml_options['Database']['pass'],db=yaml_options['Database']['dbname'] )
        cur = database.cursor()
        return database, cur

    except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0],e.args[1])
        sys.exit(1)


#LISTA BD
def list_it(yaml):

    (db, cursor) = db_establish_conn(yaml)

    #cursor.execute("SELECT * FROM filejson LIMIT 10")
    cursor.execute("SELECT * FROM filejson")
    rows = cursor.fetchall()
    dbtime = []
    dbdport = []
    for row in rows:
        #Converte o timestamp em s
	dbtime.append(dtime(row[0]))
        dbdport.append(row[6])

    plt.scatter(dbtime,dbdport)
    plt.title("Portas do atacadas")
    plt.xlabel("Timestamp")
    plt.ylabel("portas")
    #plt.xticks([w*7*24 for w in range(10)], ['week %i' %w for w in range(10)] )
    #plt.autoscale(tight=True)
    plt.grid()
    plt.show()


    print dtime("12/07/2014-22:44:37.169789")
#PARSE DO FICHEIRO YAML
class ParseYamlConfig():
    def parse(self):
	try:
            f = open('db.yaml', 'r')
	except IOError as e:
	    print "I/O error({0}): {1}".format(e.errno, e.strerror), "ERROR !!!"
		
	self.dataMap = yaml.load(f)
	f.close()
        
        return self.dataMap;


def main():    
    yaml_options = ParseYamlConfig().parse()

    list_it(yaml_options)

 
if __name__ == "__main__":

    main()
